package com.xiaotu.web.struts2.upload;

import java.io.IOException;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.xiaotu.code.model.upload.FileUpload;
import com.xiaotu.code.model.upload.FileUploadDirConstants;
import com.xiaotu.code.service.upload.FileUploadService;
import com.xiaotu.code.util.Struts2Util;

@Results( {
		@Result(name = "uploadmain", location = "/WEB-INF/content/upload/upload.jsp"),
		@Result(name = "uploadmultiplemain", location = "/WEB-INF/content/upload/upload-multiple.jsp") })
public class FileUploadAction extends ActionSupport implements
		ModelDriven<FileUpload>, Preparable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4638112650406183021L;
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private FileUpload fileUpload;
	@Autowired
	private FileUploadService fileUploadService;

	@Override
	public FileUpload getModel() {
		return fileUpload;
	}

	@Override
	public void prepare() throws Exception {
		fileUpload = new FileUpload();
	}

	@Action("/upload/main")
	public String startUpload() {
		logger.debug("进入上传...");
		return "uploadmain";
	}

	@Action("/upload/multipleMain")
	public String startMultipleUpload() {
		logger.debug("进入上传...");
		return "uploadmultiplemain";
	}

	@Action("/upload/upload")
	public String uploadFile() throws IOException {
		logger.debug("启动上传读写...");
		fileUploadService.writeFile(FileUploadDirConstants.UPLOAD, fileUpload
				.getFileDataFileName(), fileUpload.getFileData());
		Struts2Util.renderJson("{'result':'success'}", "encoding:utf-8");
		return null;
	}

}
